﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.AnalysisServices;
using System.Text.RegularExpressions;

namespace ParallelCubeProcessor
{
    class XMLAHandler : ParallelProcessingHandler
    {
        private int _maxParallelCommands;

        private Server _server = new Server();

        public XMLAHandler(int MaxConcurrent, string ServerName)
        {
            _maxParallelCommands = MaxConcurrent;
            _server.Connect(ServerName);
            _server.CaptureXml = true;
        }

        public void ProcessDatabase(Database DB)
        {
            _server.Databases.GetByName(DB.Name).Process(ProcessType.ProcessFull);
            if (_server.CaptureLog.Count >= _maxParallelCommands)
            {
                ExecuteCaptureLog();
            }
        }

        private void ExecuteCaptureLog() 
        {
            Regex dbIdRegex = new Regex("<DatabaseID>(.+)</DatabaseID>");
            System.Console.WriteLine(string.Format("[{0}] Processing:", DateTime.Now.ToLongTimeString()));

            foreach (Match dbId in dbIdRegex.Matches(_server.ConcatenateCaptureLog(true, true)))
            {
                System.Console.WriteLine("  " + dbId.Groups[1].ToString());
            }
            //System.Console.WriteLine(_server.ConcatenateCaptureLog(true, true));
            XmlaResultCollection results = _server.ExecuteCaptureLog(true, true);

            foreach (XmlaResult result in results)
            {
                bool errorEncountered = false;

                foreach (XmlaMessage message in result.Messages)
                {
                    System.Console.WriteLine(message.Description);
                    if (message.GetType().Name == "XmlaError")
                    {
                        errorEncountered = true;
                    }
                }
                if (errorEncountered)
                {
                    throw new Exception("An error was encountered during processing");
                }
            }
            _server.CaptureLog.Clear();
        }

        public void FinishProcessing()
        {
            if (_server.CaptureLog.Count > 0)
            {
                ExecuteCaptureLog();
            }
            _server.Disconnect();
        }
    }
}
